/*
 * @Author: wuqingchun
 * @Date: 2024-09-24 13:38:01
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-10-02 18:57:13
 */
#include <cstdio>

#include "chat_errno.h"
#include "db/chat_db_mysql.h"
#include "chat_user_model.h"


int32_t CChatUserModel::Insert(const char* pcName, const char* pcPassword)
{
    char szSQL[1024];

    snprintf(szSQL, 1024, "insert into user(name, password, state) values('%s', '%s', '%s')", 
             pcName, pcPassword, "offline");

    return CChatDBMysql::GetInstance().ExecuteSQL(szSQL);
}

int32_t CChatUserModel::Query(int iID, CChatUser& refUser)
{
    char szSQL[1024];

    snprintf(szSQL, 1024, "select * from user where id=%d", iID);

    MYSQL_RES* pstResult = nullptr;

    int32_t iErr = CChatDBMysql::GetInstance().ExecuteSQL(szSQL, &pstResult);
    if (iErr != CHAT_ERR_OK || pstResult == nullptr)
    {
        return CHAT_ERR_QUERY_NULL;
    }

    int iRow = mysql_num_rows(pstResult);
    int iCol = mysql_num_fields(pstResult);

    CChatUser objUser;

    MYSQL_ROW ppcRowData = mysql_fetch_row(pstResult);
    if (ppcRowData == nullptr)
    {
        return CHAT_ERR_QUERY_NULL;
    }
    
    refUser.SetID(atoi(ppcRowData[0]));
    refUser.SetName(ppcRowData[1]);
    refUser.SetPassword(ppcRowData[2]);
    refUser.SetState(ppcRowData[3]);

    mysql_free_result(pstResult);

    return CHAT_ERR_OK;
}

int32_t CChatUserModel::Query(const char* pcName, CChatUser& refUser)
{
    char szSQL[1024];

    snprintf(szSQL, 1024, "select * from user where name='%s'", pcName);

    MYSQL_RES* pstResult = nullptr;
    int32_t iErr = CChatDBMysql::GetInstance().ExecuteSQL(szSQL, &pstResult);
    if (iErr != CHAT_ERR_OK || pstResult == nullptr)
    {
        return CHAT_ERR_QUERY_NULL;
    }

    int iRow = mysql_num_rows(pstResult);
    int iCol = mysql_num_fields(pstResult);

    CChatUser objUser;

    MYSQL_ROW ppcRowData = mysql_fetch_row(pstResult);
    if (ppcRowData == nullptr)
    {
        return CHAT_ERR_QUERY_NULL;
    }
    
    refUser.SetID(atoi(ppcRowData[0]));
    refUser.SetName(ppcRowData[1]);
    refUser.SetPassword(ppcRowData[2]);
    refUser.SetState(ppcRowData[3]);

    mysql_free_result(pstResult);

    return CHAT_ERR_OK;
}

int32_t CChatUserModel::UpdateState(CChatUser& refUser)
{
    char szSQL[1024];

    snprintf(szSQL, 1024, "update user set state = '%s' where id=%d", refUser.GetState().c_str(),
             refUser.GetID());
    return CChatDBMysql::GetInstance().ExecuteSQL(szSQL);
}

int32_t CChatUserModel::ResetState()
{
    char szSQL[1024];
    snprintf(szSQL, 1024, "update user set state = 'offline' where state = 'online'");
    return CChatDBMysql::GetInstance().ExecuteSQL(szSQL);
}